package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.domain.db.Announcement;
import com.tanhua.domain.vo.AnnouncementVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.AnnouncementApi;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Size;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class AnnounService {

    @Reference
    private AnnouncementApi announcementApi;

    /**
     * 查询公告列表
     */
    public ResponseEntity announcements(int page, int pagesize) {
        //1、调用API查询分页数据 ipage对象
        IPage<Announcement> iPage = announcementApi.findAll(page, pagesize);
        //2、获取所有的公告对象
        List<Announcement> records = iPage.getRecords();
        //3、一个公告对象，转化为一个vo对象
        List<AnnouncementVo> list = new ArrayList<>();

        for (Announcement record : records) {
            AnnouncementVo vo = new AnnouncementVo();
            BeanUtils.copyProperties(record,vo);
            if(record.getCreated() != null) {
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd hh:mm").format(record.getCreated()));
            }
            list.add(vo);
        }
        //4、构造需要的分页对象，PageResult
        PageResult result = new PageResult(page, pagesize,(int)iPage.getTotal(),list);
        //5、构造返回值
        return ResponseEntity.ok(result);
    }
}
